package top.kaoshanji.r1ch04a;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * 代码清单-r1ch04a-79页b：通过Java反射机制以一种间接的方式操控目标类
 * @author kaoshanji
 * ^_^
 * create time 2025/5/4 17:15
 */
public class ReflectTest {

    public static Car initByDefaultConst() throws Throwable {

        // 通过类加载器获取 Car 类对象
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class clazz = classLoader.loadClass("top.kaoshanji.r1ch04a.Car");

        // 构造器
        Constructor constructor = clazz.getDeclaredConstructor((Class[]) null);
        Car car = (Car) constructor.newInstance();

        // 调用 set 方法，为属性赋值
        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "红旗CA72");

        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "黑色");

        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 200);

        return car;
    }

    public static void main(String[] args) throws Throwable {
        Car car = initByDefaultConst();
        car.introduce();

    }

}
